<template>
  <div class="tech-card p-6 min-h-[600px]">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold text-white">训练数据</h2>
      <div class="flex gap-2">
        <button class="tech-button-outline" @click="showAddModal = true">添加训练数据</button>
        <button class="tech-button" @click="fetchTrainingData" :disabled="loading">刷新</button>
      </div>
    </div>
    <div v-if="loading" class="text-center text-gray-400 py-8">加载中...</div>
    <div v-else>
      <table class="min-w-full divide-y divide-gray-700 bg-gray-800 rounded shadow overflow-x-auto">
        <thead class="bg-gray-900">
          <tr>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-400 uppercase w-20">操作</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-400 uppercase w-48">问题</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-400 uppercase">内容</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in pagedData" :key="item.id" class="hover:bg-gray-700">
            <td class="px-4 py-2 align-top">
              <button class="text-red-400 border border-red-400 rounded px-2 py-1 hover:bg-red-900/30 transition-colors" @click="remove(item.id)">删除</button>
            </td>
            <td class="px-4 py-2 align-top break-all text-gray-100" :title="item.question">{{ item.question || 'null' }}</td>
            <td class="px-4 py-2 align-top whitespace-pre-line break-all text-gray-100" :title="item.content">{{ item.content }}</td>
          </tr>
        </tbody>
      </table>
      <div v-if="trainingData.length === 0" class="text-center text-gray-400 py-8">暂无训练数据</div>
      <div v-else class="flex justify-between items-center mt-4 text-gray-300 text-sm">
        <div>
          显示: {{ startIdx + 1 }} - {{ endIdx }} / {{ trainingData.length }}
        </div>
        <div class="flex gap-2">
          <button class="tech-button-outline px-3 py-1" :disabled="page === 1" @click="page--">上一页</button>
          <span>第 {{ page }} / {{ totalPages }} 页</span>
          <button class="tech-button-outline px-3 py-1" :disabled="page === totalPages" @click="page++">下一页</button>
        </div>
      </div>
    </div>

    <!-- 添加训练数据弹窗（深色风格，位置更靠上，全部中文） -->
    <div v-if="showAddModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-start justify-center z-50" style="overflow-y:auto;">
      <div class="bg-gray-900 rounded-xl shadow-2xl p-8 w-full max-w-xl relative mt-[10vh] border border-gray-700">
        <button class="absolute top-4 right-4 text-gray-400 hover:text-white text-2xl font-bold" @click="showAddModal = false">×</button>
        <h2 class="text-3xl font-bold text-white mb-6">添加训练数据</h2>
        <form @submit.prevent="submitAdd">
          <div class="mb-6">
            <div class="font-semibold text-gray-100 mb-2">训练数据类型</div>
            <div class="space-y-3">
              <label class="flex items-start gap-2 cursor-pointer">
                <input type="radio" v-model="addForm.type" value="ddl" class="mt-1" />
                <div>
                  <span class="font-bold text-white">DDL（表结构）</span><br />
                  <span class="text-gray-400 text-sm">用于定义数据库结构的 CREATE TABLE 语句。</span>
                </div>
              </label>
              <label class="flex items-start gap-2 cursor-pointer">
                <input type="radio" v-model="addForm.type" value="documentation" class="mt-1" />
                <div>
                  <span class="font-bold text-white">文档说明</span><br />
                  <span class="text-gray-400 text-sm">可为任意文本型文档，建议内容简明聚焦单一主题。</span>
                </div>
              </label>
              <label class="flex items-start gap-2 cursor-pointer">
                <input type="radio" v-model="addForm.type" value="sql" class="mt-1" />
                <div>
                  <span class="font-bold text-white">SQL 语句</span><br />
                  <span class="text-gray-400 text-sm">可为任意可用的 SQL 查询语句，越多越好。</span>
                </div>
              </label>
            </div>
          </div>
          <div class="mb-6">
            <div class="font-semibold text-gray-100 mb-2">内容</div>
            <textarea v-model="addForm.content" class="w-full border border-gray-700 rounded-md p-3 text-gray-100 bg-gray-800 min-h-[100px] focus:ring-2 focus:ring-cyber-cyan-500 focus:border-cyber-cyan-500 outline-none" :placeholder="contentPlaceholder"></textarea>
          </div>
          <button type="submit" class="w-full bg-tech-blue-600 hover:bg-tech-blue-700 text-white text-lg font-bold py-3 rounded-md transition-all duration-200" :disabled="addLoading">保存</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const trainingData = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = 10
const showAddModal = ref(false)
const addLoading = ref(false)
const addForm = ref({ type: 'ddl', question: '', content: '' })

const totalPages = computed(() => Math.max(1, Math.ceil(trainingData.value.length / pageSize)))
const startIdx = computed(() => (page.value - 1) * pageSize)
const endIdx = computed(() => Math.min(page.value * pageSize, trainingData.value.length))
const pagedData = computed(() => trainingData.value.slice(startIdx.value, endIdx.value))

const contentPlaceholder = computed(() => {
  if (addForm.value.type === 'ddl') return 'CREATE TABLE ...'
  if (addForm.value.type === 'sql') return 'SELECT column_1, column_2 FROM table_name;'
  return '请输入文档内容'
})

async function fetchTrainingData() {
  loading.value = true
  try {
    const res = await fetch('/api/v0/get_training_data')
    const data = await res.json()
    if (data && data.df) {
      trainingData.value = JSON.parse(data.df)
      if (page.value > totalPages.value) page.value = totalPages.value
    } else {
      trainingData.value = []
    }
  } catch (e) {
    trainingData.value = []
  } finally {
    loading.value = false
  }
}

async function remove(id) {
  if (!confirm('确定要删除该训练数据吗？')) return
  try {
    await fetch('/api/v0/remove_training_data', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id })
    })
    fetchTrainingData()
  } catch (e) {
    alert('删除失败')
  }
}

async function submitAdd() {
  addLoading.value = true
  try {
    const body = {
      question: addForm.value.question || undefined,
      ddl: addForm.value.type === 'ddl' ? addForm.value.content : undefined,
      sql: addForm.value.type === 'sql' ? addForm.value.content : undefined,
      documentation: addForm.value.type === 'documentation' ? addForm.value.content : undefined
    }
    const res = await fetch('/api/v0/train', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    })
    if (res.ok) {
      showAddModal.value = false
      addForm.value = { type: 'ddl', question: '', content: '' }
      fetchTrainingData()
    } else {
      alert('添加失败')
    }
  } catch (e) {
    alert('添加失败')
  } finally {
    addLoading.value = false
  }
}

onMounted(fetchTrainingData)
</script>

<style scoped>
.tech-card {
  background: rgba(31, 41, 55, 0.95);
  border-radius: 0.75rem;
  box-shadow: 0 4px 24px 0 rgba(0,0,0,0.15);
}

th, td {
  font-size: 14px;
}

th {
  font-weight: 600;
}

.break-all {
  word-break: break-all;
}

.whitespace-pre-line {
  white-space: pre-line;
}

.tech-button-outline {
  @apply bg-transparent border border-tech-blue-500 text-tech-blue-500 hover:bg-tech-blue-500/10 font-medium py-2 px-4 rounded-md transition-all duration-300 flex items-center justify-center gap-2 focus:outline-none focus:ring-2 focus:ring-cyber-cyan-500 focus:ring-opacity-50;
}
</style> 